package com.ruoyi.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.MemberCarConstants;
import com.ruoyi.common.core.domain.entity.InfoLog;
import com.ruoyi.common.core.domain.entity.ParkConfig;
import com.ruoyi.common.core.domain.entity.RuleConfig;
import com.ruoyi.common.utils.ParkingApiUtil;
import com.ruoyi.system.mapper.InfoLogMapper;
import com.ruoyi.system.mapper.ParkConfigMapper;
import com.ruoyi.system.service.ICarPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 停车缴费管理Service实现类
 *
 * @author ruoyi
 * @date 2024-09-10
 */
@Service
public class CarPayServiceImpl implements ICarPayService {

    private static final Logger log = LoggerFactory.getLogger(CarPayServiceImpl.class);

    @Autowired
    private ParkingApiUtil parkingApiUtil;

    @Autowired
    private ParkConfigMapper parkConfigMapper;

    @Autowired
    private InfoLogMapper infoLogMapper;

    /**
     * 查询车辆信息
     */
    @Override
    public AjaxResult getCarinfo(String carNo) {
        log.info("开始查询车辆信息，车牌号：{}", carNo);
        Map<String, Object> result = parkingApiUtil.getCarinfo(carNo);
        log.info("调用外部API查询车辆信息返回结果：{}", result);
        Object resCode = result.get("resCode");

        if (MemberCarConstants.SUCCESS_CODE_STRING.equals(String.valueOf(resCode))) {
            log.info("API调用成功，处理返回数据");
            Object dataObj = result.get("data");
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataObj;
            if (!dataList.isEmpty()) {
                Map<String, Object> firstItem = dataList.get(0);
                Map<String, Object> attributes = (Map<String, Object>) firstItem.get("attributes");
                if (attributes != null) {
                    String parkCode = (String) attributes.get("parkCode");
                    log.info("获取到停车场编码：{}", parkCode);
                    // 将 parkCode 添加到结果中（可选）
                    firstItem.put("parkCode", parkCode);

                    // 查询规则配置
                    ParkConfig parkConfig = new ParkConfig();
                    parkConfig.setParkId(parkCode);
                    log.info("开始查询停车场规则配置，parkId：{}", parkCode);
                    RuleConfig ruleConfig = parkConfigMapper.selectRuleConfigByParkCode(parkConfig);

                    // 将 ruleConfig 添加到结果中
                    if (ruleConfig != null) {
                        attributes.put("ruleConfig", ruleConfig);
                        log.info("成功获取规则配置并添加到结果中");
                    } else {
                        log.warn("未找到停车场规则配置，parkId：{}", parkCode);
                    }
                } else {
                    log.warn("返回数据中未找到attributes");
                }
            } else {
                log.warn("返回数据列表为空");
            }
        } else {
            log.error("API调用失败，返回码：{}", resCode);
        }
        log.info("车辆信息查询完成，最终结果：{}", result);
        return convertToAjaxResult(result);
    }

    /**
     * 缴费操作
     */
    @Override
    public AjaxResult addChargeInfo(String carNo, String orderNo) {
        log.info("开始缴费操作，车牌号：{}，订单号：{}", carNo, orderNo);
        Map<String, Object> result = parkingApiUtil.addChargeInfo(carNo, orderNo);
        log.info("缴费操作返回结果：{}", result);


        // 保存车辆绑定时的打折日志信息
        InfoLog infoLog = new InfoLog();
        infoLog.setVehiclePlate(carNo);

//操作类型：1=进场打折，2=出场，3=通知车场已支付 ，4=车辆已进场且未享受优惠在添加车辆时打折，
// 5=进场，6=查询缴费时添加车辆但推送打折失败，7=添加车辆但推送打折失败，8=车辆已进场且未享受优惠在查询交费时添加车辆并打折
        infoLog.setActionType(3);
        infoLog.setActionTime(new Date());
        // 转换为 JSON 字符串
        infoLog.setJsonData(JSONUtil.toJsonStr(result));
        infoLogMapper.insertInfoLog(infoLog);

        return convertToAjaxResult(result);
    }

    /**
     * 时长减免
     */
    @Override
    public AjaxResult addMemberRelief(String carNo, String ticketId, Integer freeTime) {
        log.info("开始时长减免操作，车牌号：{}，票券ID：{}，减免时长：{}分钟", carNo, ticketId, freeTime);
        Map<String, Object> result = parkingApiUtil.addMemberRelief(carNo, ticketId, freeTime);
        log.info("时长减免操作返回结果：{}", result);
        return convertToAjaxResult(result);
    }

    /**
     * 金额减免
     */
    @Override
    public AjaxResult addMemberReliefSh(String carNo, String ticketId, Double amount) {
        log.info("开始金额减免操作，车牌号：{}，票券ID：{}，减免金额：{}元", carNo, ticketId, amount);
        Map<String, Object> result = parkingApiUtil.addMemberReliefSh(carNo, ticketId, amount);
        log.info("金额减免操作返回结果：{}", result);
        return convertToAjaxResult(result);
    }

    /**
     * 全免
     */
    @Override
    public AjaxResult freeFull(String carNo, String parkCode) {
        log.info("开始全免操作，车牌号：{}", carNo);
        Map<String, Object> result = parkingApiUtil.freeCharge(carNo, parkCode);
        log.info("全免操作返回结果：{}", result);

        // 保存车辆绑定时的打折日志信息
        InfoLog infoLog = new InfoLog();
        infoLog.setVehiclePlate(carNo);

        infoLog.setActionType(9);
        infoLog.setActionTime(new Date());
        // 转换为 JSON 字符串
        infoLog.setJsonData(JSONUtil.toJsonStr(result.get("jsonResult")));
        infoLogMapper.insertInfoLog(infoLog);

        return convertToAjaxResult(result);
    }

    /**
     * 将工具类返回的Map转换为AjaxResult
     */
    private AjaxResult convertToAjaxResult(Map<String, Object> resultMap) {
        if (resultMap == null) {
            log.error("转换结果为null，返回错误信息");
            return AjaxResult.error("服务调用失败");
        }

        // 假设工具类返回的成功码为0或"resCode":0
        if (resultMap.containsKey("resCode") && resultMap.get("resCode").equals(0)) {
            log.info("转换结果为成功响应");
            return AjaxResult.success(resultMap.get("data"));
        } else {
            String errorMsg = (String) resultMap.getOrDefault("resMsg", "操作失败");
            log.error("转换结果为失败响应，错误信息：{}", errorMsg);
            return AjaxResult.error(errorMsg);
        }
    }
}
